import 'dart:collection';

import 'package:dark_notes/utilities/storage.dart';
import 'package:flutter/material.dart';

class NoteModel extends ChangeNotifier {
  final List<Note> _notes = [];
  final NoteStorage storage;
  NoteModel({this.storage}) {
    this.storage.readNotes().then((List<Note> notes) {
      addAll(notes);
    });
  }

  UnmodifiableListView<Note> get notes => UnmodifiableListView(_notes);

  void add(Note note) {
    _notes.add(note);
    persistNotes();
    notifyListeners();
  }

  void addAll(List<Note> notes) {
    _notes.addAll(notes);
    persistNotes();
    notifyListeners();
  }

  void remove(Note note) {
    _notes.remove(note);
    persistNotes();
    notifyListeners();
  }

  void edit(Note note, String title, String body) {
    note.title = title;
    note.body = body;
    persistNotes();
    notifyListeners();
  }

  void persistNotes() {
    storage.writeNotes(this._notes);
  }
}

class Note {
  String title;
  String body;
  Note({this.title, this.body});

  Note.fromJson(Map<String, dynamic> data)
      : title = data['title'],
        body = data['body'];

  Map<String, dynamic> toJson() =>
      {
        'title': title,
        'body': body
      };
}
